package aFormFilter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;

/**
 * Servlet Filter implementation class FormFilter
 */
@WebFilter("/FormFilter")
public class FormFilter extends HttpFilter implements Filter {
       
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
     * @see HttpFilter#HttpFilter()
     */
    public FormFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		 // 表单参数校验
        String username = request.getParameter("username");
        String email = request.getParameter("email");

        if (username == null || username.isEmpty()) {
            request.setAttribute("error", "用户名不能为空");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        if (email == null || !email.matches("\\w+@\\w+\\.\\w+")) {
            request.setAttribute("error", "邮箱格式不正确");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }

        // 放行请求
        chain.doFilter(request, response);
    }
	

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
